package com.ruoyi.web.controller.system;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecuritySHA1Utils;
import com.ruoyi.system.domain.Point;
import com.ruoyi.system.domain.mongodb.AllSchool;
import com.ruoyi.system.domain.mongodb.Ufollows;
import com.ruoyi.system.domain.mongodb.Users;
import com.ruoyi.system.mongo.AllSchoolDao;
import com.ruoyi.system.mongo.StudentDao;
import com.ruoyi.system.mongo.UfollowsDao;
import com.ruoyi.system.service.IntepralSettingService;
import com.ruoyi.system.service.PointService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.net.www.protocol.http.HttpURLConnection;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author HP
 * @Date 2021/3/26
 * @Description TODO
 */
@RestController
@RequestMapping("/Yjt")
public class YjtLoginController {
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private AllSchoolDao allSchoolDao;
    @Autowired
    private PointService pointService;
    @Autowired
    private IntepralSettingService intepralSettingService;
    @Autowired
    private UfollowsDao ufollowsDao;
    //优教通接口
    @RequestMapping("/YjtLogin")
    public void YjtLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
        String reqUrI=request.getRequestURI();
        String reqString=request.getQueryString();
        //当前url
        String reqUrl=basePath+reqUrI;
        if(reqString!=null)
        {
            reqUrl+="?"+reqString;
        }

        String appId="FH";
        String appKey="2349sdlkf23215";
        String sso="ssoxy.czbanbantong.com";
        String ssoIp="125.46.26.47";

        //传递ut参数,请求用户信息
        if(reqString!=null && reqString.indexOf("ut=")!=-1)
        {
            PrintWriter out = response.getWriter();
            //out.print(reqUrl);
            String ut=request.getParameter("ut");
            String authUrl="http://"+sso+"/sso/ssoGrant?isPortal=0&appFlg="+appId+"&appKey="+appKey+"&ut="+ut;
            System.out.println(authUrl);
            //获取用户信息
            String authResultJson=this.getAuthResultJson(authUrl);
            System.out.println(authResultJson);
            JSONObject js = JSONObject.fromObject(authResultJson);
            //鉴权标记  1 成功  其他失败
            String authFlg=js.getString("authFlg");
            //鉴权成功或失败原因
            String authInfo=js.getString("authInfo");
            //用户信息json对象
            JSONObject userJs=js.getJSONObject("user");
            out.print(userJs.toString());

            //用户帐号
            String username=userJs.getString("username");
            //真实姓名
            String truename=userJs.getString("truename");
            //用户角色 :0 家长,4学生，2教师，3校长或学校管理员，空 管理员
            String usertype=userJs.getString("usertype");
            //电子邮件
            String email=userJs.getString("email");
            //手机号
            String link=userJs.getString("link");
            //教育机构ID 为空是平台管理员，不为空是教育机构管理员
            String eduOrgId=userJs.getString("eduOrgId");
            //头像
            String headPhoto=userJs.getString("headPhoto");
            //昵称
            String nickname=userJs.getString("nickname");
            //性别
            String sex=userJs.getString("sex");
            //学校
            JSONObject schoolJs=userJs.getJSONObject("school");
            String schoolName = schoolJs.getString("schoolName");
            //年级
            JSONObject gradeJs=userJs.getJSONObject("grade");
            //班级
            JSONArray schoolClassesJs=userJs.getJSONArray("schoolClasses");
            Users users1=new Users();
            Users users;
            if (link.equals("")){
                String password = SecuritySHA1Utils.shaEncode("123456");
                users1.setPassword(password);
                users = studentDao.queryUsername(username);
            }else{
                String password = SecuritySHA1Utils.shaEncode(link);
                users1.setPassword(password);
                users = studentDao.queryUsers(username,link);
            }

            if (headPhoto.equals("")){
                users1.setHeadimg("/img/headimg/person-icon.png");
            }else{
                users1.setHeadimg(headPhoto);
            }
            if (!email.equals("")){
                users1.setEmail(email);
            }
            AllSchool allSchool = allSchoolDao.queryByNames(schoolName);
            if (allSchool!=null){
                users1.setSchool(allSchool.get_id()!=null?new ObjectId(allSchool.get_id()):new ObjectId());
            }
            Point point=new Point();
            //用户类型 2教师 3学校管理员 4 学生，如果值是3的时候第三方平台当做2处理 0管理员
            if (usertype.equals("2")){
                users1.setRole(9);
                point.setIs_stu(0);
            }else if(usertype.equals("3")){
                users1.setRole(9);
                point.setIs_stu(0);
            }else if(usertype.equals("4")){
                users1.setRole(0);
                point.setIs_stu(1);
            }else if(usertype.equals("0")){
                users1.setRole(1);
                point.setIs_stu(0);
            }else{
                //管理员
                users1.setRole(9);
                point.setIs_stu(0);
            }
            if (users==null){
                users1.setPhoneNum(link);
                users1.setUsername(username);
                users1.setNickname(nickname);
                users1.setStatus(0);
                users1.setRealname(truename);
                String id = studentDao.saveUser1(users1);
                Ufollows ufollows=new Ufollows();
                ufollows.setUserid(new ObjectId(id));
                List list=new ArrayList();
                String yyyyMmDdHhMmSs = DateUtils.YYYY_MM_DD_HH_MM_SS;
                //ufollows.set_id(new ObjectId(userid));
                ufollows.setCreateAt(yyyyMmDdHhMmSs);
                ufollows.setFanslist(list);
                ufollows.setFolltotal(0);
                ufollows.setFollist(list);
                ufollows.setFanstotal(0);
                ufollowsDao.saveUfollows(ufollows);
                point.setUser_id(id);
                point.setPoint(0);
                point.setAccumulated_integral(0);
                point.setIs_delete(0);
                pointService.savePoint(point);
                intepralSettingService.addIntepral(id,2);
                //用户第一次登录 这个1就是标识符 如果有的话就是第一次登录 没有就代表登录过
                response.sendRedirect("http://localhost:3800/Sso?_id="+id+"&status=1");
            }else{
                //用户已经登录过
                response.sendRedirect("http://localhost:3800/Sso?_id="+ users.getId()+"&status=2");
            }

        }
        //未传递ut参数，请求ut
        else
        {
            String reqUrlEncode= URLEncoder.encode(reqUrl, "UTF-8");
            String getUtUrl="http://"+sso+"/sso/getUt?isPortal=1&appId="+appId+"&appKey="+appKey+"&returnUrl="+reqUrlEncode;
            response.sendRedirect(getUtUrl);
            return;
        }
    }

    private String getAuthResultJson(String authUrl)
    {
        String authResultJson=null;

        URL url = null;
        HttpURLConnection conn = null;

        StringBuffer sb = new StringBuffer();
        InputStream in=null;
        BufferedReader br=null;
        try
        {

            url = new URL(authUrl);//构造好这个URL对象，参数就是你要通信的servlet地址，实际测试的时候，这个URL可以从Properties文件中取得，以增加灵活性
            conn = (HttpURLConnection) url.openConnection();//打开，创建Connection对象

            conn.setRequestMethod("GET"); //设定请求方式为POST
            conn.setDoOutput(true); //一定要设为true,因为要发送数据

            conn.setDoInput(true);


            int res = conn.getResponseCode();
            //logger.info("http status ��"+res);
            if (res == 200)
            {
                //接收数据
                in = conn.getInputStream();
                br = new BufferedReader(new InputStreamReader(in,"GBK"));
                char[] bc = new char[1024];
                int len = 0;
                while ((len = br.read(bc)) > 0)
                {
                    sb.append(bc, 0, len);
                }
            }
            authResultJson=sb.toString();
            br.close();
            in.close();
        }
        catch (Exception e)
        {
            //e.printStackTrace();
        }
        finally
        {
            br=null;
            in=null;
            conn.disconnect();
            conn=null;
            sb=null;
            url=null;
        }

        return authResultJson;
    }
}
